<?php
if (sizeof($_POST) == 2)
{
	/////////////////////////////////////////////////
	function twofa($mysqli, $un, $pw)
	{
		$res = $mysqli->query("select isia from users where un like '$un' and pw like '$pw'");
		$ob = $res->fetch_object();
		if ($ob->isia == 'y')
		{
			implAuth();
		}
		else
		{
			$res = $mysqli->query("select otppref from users where un like '$un' and pw like '$pw'");
			$ob = $res->fetch_object();
			if ($ob->otppref == 'e' || $ob->otppref == null)
			{
				$res->close();
				sendOtp('e', $mysqli, $un, $pw);
			}
			else
			{
				$res->close();
				sendOtp('p', $mysqli, $un, $pw);
			}
		}
	}


	//////////////////////////////////////////////////
	function implAuth($mysqli, $un)
	{
		$x = 0;
		do
		{
			// generate s_code
			$s_code = sha1(time() . rand() . rand());

			$res = $mysqli->query("insert into ia values ('$s_code', '$un', " . time() . ")");
		} while (!$res && $x++ < 100);


		$script = <<<EOT

	<script>
	 
	
		if (navigator.geolocation) {
			  var timeoutVal = 60 * 1000;
				navigator.geolocation.getCurrentPosition(
				   reportPosition, 
						displayError,
							{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
							  );
		}
		else {
			  alert("Geolocation is not supported by this browser");
		}

		function reportPosition(position) {
			document.write("please wait...");
			xmlhttp = new XMLHttpRequest();
			xmlhttp.open("POST","locReport.php");
			xmlhttp.onreadystatechange = function()
			{   
				if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
				{   
					document.write(xmlhttp.responseText);
				}   
			}   
			var fd = new FormData();

			fd.append('s_code',
EOT;
	$script .= "'$s_code');fd.append('un', '$un');";
	$script .= <<<EOT
			fd.append('lat', position.coords.latitude);
			fd.append('lon', position.coords.longitude);
			fd.append('acc', position.coords.accuracy);
			xmlhttp.send(fd);
		}

		function displayError(error) {
			  var errors = { 
					  1: 'Permission denied',
					  2: 'Position unavailable',
					  3: 'Request timeout'
				};
			  alert("Error: " + errors[error.code]);
		}


	</script>


EOT;

	echo $script;
	

	}

	
	/////////////////////////////////////////////////
	function sendOtp($otptype, $mysqli, $un, $pw)
	{
		require_once "Mail.php";
		$from = "server1.2FA";
		$to = ""; // needs to be HERE!
		$subject = "Your server1 2FA code";
		$host = "ssl://smtp.gmail.com";
		$port = "465";
		$username = "cs249project3"; 
		$password = "project3";
		
		$s = <<<EOT
			<!doctype html>
			<html>
				<head>
					<title>Server1 - 2FA Authentication</title>
					<meta charset="utf-8">
				</head>
				<body>
					<p>An OTP code has been sent to your

EOT;

		if ($otptype == 'e')
		{
			$res = $mysqli->query("select email from users where un like '$un' and pw like '$pw'");
			$ob = $res->fetch_object();
			if ($ob->email == null)
			{
				echo "Error! Email required for 2FA!";
				$res->close();
				exit();
			}
			$to = $ob->email;
			$res->close();
			
			$s .= " email address. <br />Please enter the code into the box below. </p>";
		}	
		else
		{
			$res = $mysqli->query("select phone from users where un like '$un' and pw like '$pw'");
			$ob = $res->fetch_object();
			if ($ob->phone == null)
			{
				echo "Error! Phone number required for 2FA!";
				$res->close();
				exit();
			}
			$to = $ob->phone;
			$res->close();
			
			$s .= "phone number. <br />Please enter the code into the box below </p>";
		}
	
		$otpcode = sha1(time());
		$sha1un = sha1($un);
		if (strlen($otpcode) == 40 && strlen($sha1un) == 40)
		{
			$res = $mysqli->query("select count(*) as count from 2fa where sha1un like '$sha1un'");
			$ob = $res->fetch_object();
			if ($ob->count == 0)
			{
				$res->close();
				$res = $mysqli->query("insert into 2fa values ('$sha1un', '$otpcode')");
			}
			else
			{
				$res->close();
				$res = $mysqli->query("update 2fa set code = '$otpcode' where sha1un like '$sha1un'");
			}
		}
		else
		{
			$res->close();
			echo "Error: SHA-1 size is not 40 chars!";
			exit();
		}

		$body = "Your OTP code is: $otpcode";
		$headers = array ('From' => $from,
		'To' => $to,
		'Subject' => $subject);
		$smtp = Mail::factory('smtp',
		array ('host' => $host,
		  'port' => $port,
		  'auth' => true,
		  'username' => $username,
		  'password' => $password));
		$mail = $smtp->send($to, $headers, $body);

		if (PEAR::isError($mail)) 
		{
			echo("Error: cannot send mail!");
			$mysqli->close();
			exit();
		} 
		else 
		{
			$s .= 		'<form name="2FA" method="post" action="2FA.php">
							<input type="hidden" name="sha1un" value="' . $sha1un . '" />
							<input type="hidden" name="un" value="' . $un . '" />
							<input type="text" name="otpcode" size="50" />
							&nbsp;&nbsp;&nbsp;<input type="submit" value="Go">
						</form>
					</body>
				</html>';
			echo $s;
		}
	}
	
	
	//////////////////////////////////////////
	$un = $_POST['username'];
	$pw = $_POST['password'];
	$isunempty = false;
	$ispwempty = false;
	
	if (strlen(trim($un)) == 0)
	{
		$isunempty = true;
	}
	if (strlen(trim($pw)) == 0)
	{
		$ispwempty = true;
	}
	
	$s = <<<EOT
		<!doctype html>
		<html>
			<head>
				<title>Server1 - Login</title>
				<meta charset="utf-8">
		
				<style>
	
	
				</style>
		
			</head>
	
			<body>
				<p>Please enter your username and password</p>
		
				<form id="login" name="login" method="post" action="login.php" autocomplete="off">
			
					<table>
						<tr>
							<td width="150">Username</td>
							<td><input type="text" name="username" id="username" /></td>
						</tr>
						<tr>
							<td width="150">Password</td>
							<td><input type="password" name="password" id="password" /></td> 
						</tr>
						<tr>
							<td colspan="2" align="center" style="padding:10px"><input type="submit" value="Submit" /></td>
						</tr>
					</table>

				</form>
				
				<p style="color:red">
		
EOT;
	
	if (!($isunempty || $ispwempty))
	{
		$mysqli = new mysqli('localhost', 'root', 'project3', 'server1');
		if ($mysqli->connect_errno)
		{
			echo "database connection error!";
			exit();
		}
		else
		{
			$sql = "select count(*) as count from users where un like '$un' and pw like '$pw'";
			$res = $mysqli->query($sql);
			$ob = $res->fetch_object();
			if ($ob->count != 1)
			{
				$s .= "Either the username and/or password did not match! <br /></p</body></html>";
				echo $s;
				$res->close();
			}
			else
			{
				$res = $mysqli->query("select * from users where un like '$un' and pw like '$pw'");
				$ob = $res->fetch_object();

				
				if ($ob->isia == 'y')
				{
					implAuth($mysqli, $un);
					$res->close();
					$mysqli->close();
					exit;
				}

				if ($ob->is2fa == null || $ob->is2fa == 'n')
				{
				$s = <<<EOT
					<!doctype html>
					<html>
						<head>
							<title>Server1 - Security Settings</title>
							<meta charset="utf-8">
					
							<script>
							function savesettings()
							{   
								var is2fa = (document.getElementById('2fa').checked ? true : false);
								var otptype = (document.getElementById('otppref-e').checked ? 'e' : 'p' );
								var isia = (document.getElementById('ia').checked ? true : false);
								xmlhttp = new XMLHttpRequest();
								xmlhttp.open("POST","savesettings.php");
								xmlhttp.onreadystatechange = function()
								{   
									if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
									{   
										if (xmlhttp.responseText == "0")
										{
											alert("Your settings have been saved");
											return;
										}
										if (xmlhttp.responseText == "4")
										{
											alert("Nothing changed!");
											return;
										}
										alert('Your setting have NOT been changed because: ' + xmlhttp.responseText);
									}   
								}   
								var fd = new FormData();
								fd.append('un', 
EOT;

								$s .= " '$un');";
								$s .= <<<EOT
								fd.append('is2fa', is2fa);
								fd.append('otptype', otptype);
								fd.append('isia', isia);
								xmlhttp.send(fd);
							}   
							function restoreIA()
							{
								xhr = new XMLHttpRequest();
								xhr.open("POST", "restoreIA.php");
								xhr.onreadystatechange = function()
								{
									if (xhr.readyState == 4 && xhr.status == 200)
									{
										if (xhr.responseText == "0")
										{
											alert("Please check your email/phone for a message regarding restoring your account.");
											return;
										}
										alert("Error: " + xhr.responseText);
									}
								}
							

								var fd = new FormData();
								fd.append('un', 
EOT;

								$s .= " '$un');";
								$s .= <<<EOT
								xhr.send(fd);
							}   
							</script>

						</head>
				
						<body>
							<h1>Security Settings</h1>
							<table>
								<tr>
									<td width="150">Use 2FA</td>
									<td><input type="checkbox" name="cbs[]" id="2fa" value="2fa" 
EOT;

				$res = $mysqli->query("select * from users where un like '$un' and pw like '$pw'");
				$ob = $res->fetch_object();
				
				if ($ob->is2fa == 'y')
				{
					$s .= "checked=\"yes\"";
				}

				$s .= <<<EOT
									/></td>
								</tr>
								<tr>
									<td>OTP method</td>
EOT;
				if ($ob->otppref == "e")
				{
					$s .= '<td><input type="radio" name="otppref" id="otppref-e" value="e" checked/>Email &nbsp;&nbsp;&nbsp;<input type="radio" name="otppref" id="otppref-p" value="p" />SMS</td>';
				}
				else
				{
					$s .= '<td><input type="radio" name="otppref" id="otppref-e" value="e" />Email &nbsp;&nbsp;&nbsp;<input type="radio" name="otppref" id="otppref-p" value="p" checked/>SMS</td>';
				}

				$s .= <<<EOT

								</tr>
								<tr>
									<td width="150">Use Impl. Auth.</td>
									<td><input type="checkbox" name="cbs[]" id="ia" value="ia" 
EOT;
				if ($ob->isia == 'y')
				{
					$s .= "checked=\"yes\"";
				}

				$s .= <<<EOT
									/></td>
								</tr>
								<tr>
									<td colspan="2" align="center" style="padding: 25px 0px" ><input type="submit" value="Save" onclick="savesettings()"/></td>
								</tr>
								<tr>
									<td colspan="2" align="center" style="padding: 25px 0px" ><input type="submit" value="Restore your IA account" onclick="restoreIA()"/></td>
								</tr>
							</table>
						</body>
					</html>
EOT;
					echo $s;
					$res->close();
				}
				else
				{
					twofa($mysqli, $un, $pw);
				}
				
				
			}
			
			
		}
		
		$mysqli->close();
		exit();
	}

	
	if ($isunempty)
	{
		$s .= 'Please enter a username! <br />';
	}

	if ($ispwempty)
	{
		$s .= 'Please enter a password! <br/>';
	}
	
	$s .= '</p</body></html>';
	echo $s;
}
	
	
	
	
	
?>
